package com.youlu.campus.web.invite.controller;

import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityTaskInfo;
import com.youlu.campus.entity.VO.UserInviteRequest;
import com.youlu.campus.entity.VO.req.UserInviteQueryVO;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.invite.UserInviteService;
import com.youlu.campus.web.common.base.RequestContext;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 邀请信息
 *
 * @author: zgz
 * @date: 2020/11/23 13:36
 */
@Slf4j
@RestController
public class UserInviteController {

    @Autowired
    private UserInviteService userInviteService;
    @Autowired
    private ActivityService activityService;

    /**
     * 创建邀请记录
     */
    @PostMapping("/mini-app/invite/create")
    public QResult createInvite(@RequestBody @Valid UserInviteRequest request) {
        request.setUserPO(RequestContext.getCurUser());
        request.setAppId(request.getAppId());
        request.setPlatform(request.getPlatform());
        return QResult.success(userInviteService.createInvite(request));
    }

    /**
     * 活动邀请记录
     *
     * @param req 邀请记录查询参数
     * @return 邀请记录列表
     */
    @PostMapping("/mini-app/invite/list")
    public QResult getUserInvites(@RequestBody UserInviteQueryVO req) {
        req.setUserId(RequestContext.getUserId());
        if (StringUtils.isBlank(req.getTaskId())) {
            ActivityTaskInfo taskInfo = activityService.findActivityTaskInfo(req.getActivityId(), req.getTaskBizType());
            if (Objects.isNull(taskInfo)) {
                log.error(":>>> 活动:{} 没有配置邀请任务", req.getTaskId());
                throw new BusinessException("活动没有配置邀请任务,请咨询客服");
            }
            req.setTaskId(taskInfo.getId());
        }
        req.setPlatform(RequestContext.getCurPlatform());
        return QResult.success(activityService.getUserInviteRecord(req));
    }

    /**
     * 获取被邀请人数
     *
     * @param activityId 活动ID
     * @param userId 用户ID（非必传，默认当前用户）
     * @return 被邀请人数
     */
    @GetMapping("/mini-app/invited/count")
    public QResult getInvitedCount(@RequestParam("activityId") String activityId,
                                   @RequestParam(value = "userId", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            userId = RequestContext.getUserId();
        }
        return QResult.success(userInviteService.getInvitedNumNew(userId, activityId));
    }
}